<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h2>登录</h2>
      </div>
      <div class="auth-body">
        <el-form :model="form" :rules="rules" ref="loginForm">
          <el-form-item prop="usermark">
            <el-input
                v-model="form.usermark"
                placeholder="学号或邮箱"
                class="auth-input"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
                v-model="form.password"
                type="password"
                placeholder="密码"
                show-password
                class="auth-input"
            ></el-input>
          </el-form-item>
          <div class="auth-options">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <router-link to="/forgot-password" class="forgot-password">
              忘记密码?
            </router-link>
          </div>
          <el-button
              type="primary"
              class="auth-button"
              @click="handleLogin"
              :loading="loading"
          >
            登录
          </el-button>
        </el-form>
      </div>
      <div class="auth-footer">
        <span>还没有账号? </span>
        <router-link to="/register" class="auth-link">立即注册</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from 'axios';
import {useStore} from "vuex";

const router = useRouter();
const loginForm = ref(null);
const loading = ref(false);
const rememberMe = ref(false);
const store = useStore();

const form = ref({
  usermark: "",
  password: "",
});

const rules = {
  usermark: [{ required: true, message: "请输入学号或邮箱", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

const handleLogin = async () => {
  try {
    await loginForm.value.validate();
    loading.value = true;

    // 调用真实登录接口
    const response = await axios.post('/user/login', {
      userid: form.value.usermark,
      email: form.value.usermark,
      password: form.value.password
    });

    if (response.data.status === 200) {
      const { jwt, userId, username, role } = response.data.data;

      // 存储token和用户信息
      localStorage.setItem('token', jwt);
      localStorage.setItem('userInfo', JSON.stringify({
        userId,
        username,
        role
      }));

      // 使用 Vuex action 更新状态
      await store.dispatch('updateAuth', {
        token: jwt,
        userInfo: { userId, username, role }
      });

      // 根据角色跳转不同页面
      if (role === 'ROLE_ADMIN') {
        router.push('/admin/dashboard');
      } else {
        router.push('/');
      }

      ElMessage.success("登录成功");
    } else {
      ElMessage.error(response.data.msg || "登录失败");
    }
  } catch (error) {
    console.error("登录错误:", error);
    ElMessage.error(error.response?.data?.msg || "网络错误，请稍后重试");
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 70vh;
  background-color: #f5f5f5;
  padding: 20px;
  overflow: hidden;
  box-sizing: border-box;
}

.auth-card {
  width: 100%;
  max-width: 400px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 32px;
  margin: 0 auto;
}

.auth-header {
  text-align: center;
  margin-bottom: 24px;
}

.auth-header h2 {
  color: #262626;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.auth-input {
  width: 100%;
}

.auth-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forgot-password {
  color: #1890ff;
  text-decoration: none;
  font-size: 14px;
}

.forgot-password:hover {
  text-decoration: underline;
}

.auth-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.auth-footer {
  text-align: center;
  margin-top: 16px;
  color: #8c8c8c;
  font-size: 14px;
}

.auth-link {
  color: #1890ff;
  text-decoration: none;
}

.auth-link:hover {
  text-decoration: underline;
}
</style>